<?php
/**
 * 题库讲评
 */
namespace Admin\Frontend\Controllers;
use Helpers\Tool;
use Helpers\MainFun;
use Helpers\TemplateFun;
use Helpers\AssetsImport;
use Phalcon\Di;
use Phalcon\Db\Column;


class BuysController extends ControllerBase
{
    const Key     = 'xhtest';       //文件服务器key
    const Service = 'buyServiceDB';

    /**
     * 初始化时连接数据库
     *
     * create by zsc 20170503
     */
    protected function initialize()
    {
        error_reporting(E_ERROR);
    }

    /**
     *连接数据库
     *
     * create by zsc 20170503
     */
    public static function setDBService()
    {
        $dbConfig = MainFun::getConfigByName(self::Service);
        Di::getDefault()->setShared(self::Service, function() use ($dbConfig){
            $connection = new DbAdapter($dbConfig);
            if(APP_DEV){
                $profiler = new \Phalcon\Db\Profiler();
                $eventsManager = new \Phalcon\Events\Manager();
                $logger = new \Phalcon\Logger\Adapter\File(BASE_PATH . "/public/logs/sql.log");
                $eventsManager->attach('db', function($event, $connection) use ($logger, $profiler) {
                    if ($event->getType() == 'beforeQuery') {
                        $profiler->startProfile(
                            $connection->getSQLStatement()
                        );
//                    $variables = $connection->getSQLStatement();
//                    $string = $connection->getSQLVariables();
//                    if ($string) {
//                        $variables .= '['.implode(', ', $string).']';
//                    }
//                    $logger->log($variables, \Phalcon\Logger::INFO);
                    }
                    if ($event->getType() === "afterQuery") {
                        $profiler->stopProfile();
                        $profile = $profiler->getLastProfile();
                        $logger->log(
                            $profile->getSqlStatement(). PHP_EOL .
                            'Time:' . $profile->getTotalElapsedSeconds(), \Phalcon\Logger::INFO);

                    }
                });
                $connection->setEventsManager($eventsManager);
            }

            return $connection;

        });

    }

    /**
     * #方法说明：获取优秀学生列表
     * # Created by zsc
     */
    public function excellentStudentAction(){
        MainFun::importEasyUIIntoAssets('js/buy/excellentStudent.js');
        $this->assets->addJs('assets/jquery/ajaxfileupload.js');
        AssetsImport::fileInput();
        MainFun::showNavPosition();
        $this->view->setVar('NavUl', '<ul class="breadcrumb"><li><i class="fa fa-home fa-lg"></i> 主页</li><li>购买服务</li><li>优秀学生列表</li></ul>');
        $listButtonArr = $formButtonArr = $listSearchArr = array();
        $listSearchArr[] = ['type'=>'text', 'id'=>'List_Search', 'name'=>'List_Search', 'label'=>'搜索： '];

            $listButtonArr[] = ['id'=>'bt_List_Add', 'text'=>'添加优秀学生', 'plain'=>'true', 'icon'=>'fa-plus'];
            $formButtonArr[] = array('id'=>'bt_Form_Add', 'text'=>'增加', 'class'=>'disabled');
            $this->view->setVar('AddEdit', true);


            $formButtonArr[] = array('id'=>'bt_Form_Edit', 'text'=>'修改', 'class'=>'disabled');
            $this->view->setVar('AddEdit', true);

        if(MainFun::checkUserPower('Res_App_RPackList_Del')){
            $listButtonArr[] = ['id'=>'bt_List_Del', 'text'=>'删除', 'plain'=>'true', 'icon'=>'fa-trash'];
        }

        $this->view->setVars([
            'List'          => TemplateFun::createList('List', 'Buy_ExcellentStudent', [
                'searchToolbar' => TemplateFun::createSearchToolBar($listSearchArr, true),
                'buttonToolbar' => TemplateFun::createButtonToolBar($listButtonArr)
            ]),

            'FormButton'    => TemplateFun::createButtonToolBar($formButtonArr)
        ]);
        $this->view->pick('buy/excellentStudent');
    }

    /**
     * #方法说明：获取优秀学生列表数据
     * # Created by zsc
     */
    public function getExcellentStudentAction(){
        $this->view->disable();
        $parameters = [

        ];
        $data = MainFun::runModelPaginator('\\Admin\\Models\\buy\\ExcellentStudent', $parameters, true);
        $this->response->setJsonContent($data)->send();



    }


    /**
     * #方法说明： 修改学生信息
     * # Created by zsc
     */
    public function modifyExcellentStudentAction(){
        $this->view->disable();
        $this->request->isPost() or die;
        $realData = MainFun::getRealData($this->request->getPost());
        $model = \Admin\Models\buy\ExcellentStudent::createRecord($realData);
        $new = $model->save() ? false : true;
        //MainFun::checkUserPower($new ? $powerTag . '_Add' : $powerTag . '_Edit') or die('无操作权限！');
        var_dump($new);exit;
        $new && die(MainFun::showMessageModal(($new ? '新增' : '修改') . '失败'));
    }



    /**
     * 上传资源包并返回相应信息
     *
     * create by ck 20161218
     */
    public function uploadBuyAction()
    {
        set_time_limit(0);
        $this->view->disable();
       $this->request->hasFiles() or die;
        $appParseInfo = MainFun::getConfigByName('appParse');
        $filePath = $appParseInfo['tempPath'];
        $filePath or $filePath = '/Mailserver/cache/temp/';
        foreach($this->request->getUploadedFiles() as $file){
            $fileName = $file->getName();
            $fileSuffix = explode('.', $fileName);
            $fileSuffix = end($fileSuffix);
            $fullPath = $filePath . time().rand(0,100000).'.'.$fileSuffix;
            $result =  $file->moveTo($fullPath);
            return $result?$fullPath:false;
        }
    }




    /**
     * #方法说明：激活学生列表
     * # Created by zsc
     */
    public function activeStudentAction()
    {
        MainFun::importEasyUIIntoAssets('js/buy/getActiveStudent.js');
        AssetsImport::fileInput();
        MainFun::showNavPosition();
        $this->view->setVar('NavUl', '<ul class="breadcrumb"><li><i class="fa fa-home fa-lg"></i> 主页</li><li>购买服务</li><li>学生列表</li></ul>');
        $listButtonArr = $formButtonArr = $listSearchArr = array();
        if(MainFun::checkUserPower('Res_App_RPackList_Add')){
            $listButtonArr[] = ['id'=>'bt_List_Add', 'text'=>'导入', 'plain'=>'true', 'icon'=>'fa-plus'];
            $formButtonArr[] = ['id'=>'bt_Form_Add', 'text'=>'增加', 'class'=>'disabled'];
            $this->view->setVar('AddEdit', true);
        }
        if(MainFun::checkUserPower('Res_App_RPackList_Del')){
            $listButtonArr[] = ['id'=>'bt_List_Del', 'text'=>'删除', 'plain'=>'true', 'icon'=>'fa-trash'];
        }
        if(MainFun::checkUserPower('Res_App_RPackList_Contact')){

        }

        $this->view->setVars([
            'List'          => TemplateFun::createList('List', 'Buy_ActiveStudent', [
                'searchToolbar' => TemplateFun::createSearchToolBar($listSearchArr, true),
                'buttonToolbar' => TemplateFun::createButtonToolBar($listButtonArr)
            ]),
        ]);
        $this->view->pick('buy/activeStudent');
    }

    /**
     * #方法说明：获取学生激活
     * # Created by zsc
     */
    public function getActiveStudentAction(){





    }

}

